URL='http://localhost:8601/';
var table = layui.table;
var form = layui.form;
var token= localStorage.getExpire("token");
$(function () {
    table.render({
        xhrFields: {
            withCredentials: true
        },
        headers:{"Authorization":token},
        elem: '#demo',
        height: 550,
        page: true,
        url: URL+'getAdminUser',
        method: 'post',
        toolbar: '#toolbarDemo',
        cols: [[
          /*  {
                field: 'user_userface',
                title: '',
                width: 52,
                templet: '<div><img style="margin-left:12px;height:25px;width:25px;border-radius:50%;line-height:50px!important;" src="{{ d.user_userface}}"></div>'
            }
            , */{field: 'user_username', title: '用户姓名', width: 100, align: 'center'}
            , {field: 'user_nickname', title: '博客网名', width: 100, align: 'center'}
            , {field: 'user_phoneNumber', title: '手机号码', width: 100, align: 'center'}
            , {field: 'user_enabled', title: '状态', width: 80, templet: '#titleTpl', align: 'center'}
            , {
                field: 'userLevel',
                title: '角色',
                width: 120,
                templet: '<div><a href="javascript:" class="layui-table-link">{{d.userRole.roles_name}}</a></div>'
            }
            , {fixed: 'right', width: 115, align: 'center', toolbar: '#barDemo', align: 'center'} //这里的toolbar值是模板元素的选择器
        ]]
    });
    table.on('tool(test)', function (obj) { //注：tool是工具条事件名，test是table原始容器的属性 lay-filter="对应的值"
        var data = obj.data; //获得当前行数据
        var layEvent = obj.event; //获得 lay-event 对应的值
        var tr = obj.tr; //获得当前行 tr 的DOM对象
      if (layEvent === 'forbidden') {
            $.ajax({
                xhrFields: {
                    withCredentials: true
                },
                headers:{"Authorization":token},
                url:URL+'updateUserState',
                data:{user_enabled: data.user_enabled,
                    user_id: data.user_id},
                dataType: 'json',
                type: 'post',
                success: function (data) {
                    if(data==1){
                        layer.msg('成功200', {
                            time: 2000 //2秒关闭（如果不配置，默认是3秒）
                        }, function () {
                            table.reload('demo', {
                                xhrFields: {
                                    withCredentials: true
                                },
                                headers:{"Authorization":token},
                                url: URL+'getAdminUser'
                                , where: {} //设定异步数据接口的额外参数
                                //,height: 300
                            });
                        });

                    }else{
                        layer.msg(data.msg, {time: 3000});
                    }
                }
            })
        } else if (layEvent === 'startUsing') {
            $.ajax({
                xhrFields: {
                    withCredentials: true
                },
                headers:{"Authorization":token},
                url:URL+'updateUserState',
                data:{user_enabled: data.user_enabled,
                    user_id: data.user_id},
                dataType: 'json',
                type: 'post',
                success: function (data) {
                    if(data==1){
                        layer.msg('编辑成功200', {
                            time: 2000 //2秒关闭（如果不配置，默认是3秒）
                        }, function () {
                            table.reload('demo', {
                                xhrFields: {
                                    withCredentials: true
                                },
                                headers:{"Authorization":token},
                                url: URL+'getAdminUser'
                                , where: {} //设定异步数据接口的额外参数
                                //,height: 300
                            });
                        });

                    }else{
                        layer.msg(data.msg, {time: 3000});
                    }
                }
            })
        }
    });
});
function setFormValue() {
    $.ajax({
        xhrFields: {
            withCredentials: true
        },
        headers:{"Authorization":token},
        url:URL+'saveAdminUser',
        data:{
            user_username: $("#user_username").val(),
            user_nickname: $("#user_nickname").val(),
            user_phoneNumber: $("#user_phoneNumber").val(),
            user_userface: $("#user_userface").val(),
        },
        dataType: 'json',
        type: 'post',
        success: function (data) {
            if(data==1){
                layer.msg('成功200', {
                    time: 2000 //2秒关闭（如果不配置，默认是3秒）
                }, function () {
                    location.reload(true);
                });
            } else {
                layer.msg(data.msg, {time: 3000})
            }
        }
    })

}

function searchUsers() {
    var table = layui.table;
    var user_enabled = $("#zhuangtai").val();
    table.reload('demo', {
        xhrFields: {
            withCredentials: true
        },
        headers:{"Authorization":token},
        url: URL+'getAdminUser',
        where: {
            name: $("#userNickname").val(),
            user_enabled: user_enabled,
        } //设定异步数据接口的额外参数
        //,height: 300
    });
}
function openAdd() {
    layer.open({
        //layer提供了5种层类型。可传入的值有：0（信息框，默认）1（页面层）2（iframe层）3（加载层）4（tips层）
        type: 1,
        title: "添加管理员",
        area: ['550px', '410px'],
        maxmin: true, //允许全屏最小化
        anim: 1, //0-6的动画形式，-1不开启
        content: $('#popUpdateTest'),//引用的弹出层的页面层的方式加载修改界面表单
        success: function(layero,index){
            //在回调方法中的第2个参数“index”表示的是当前弹窗的索引。
            //通过layer.full方法将窗口放大。
            layer.full(index);
        },
        cancel: function(index, layero){
            if(confirm('确定要关闭么')){ //只有当点击confirm框的确定时，该层才会关闭
                location.reload(true);
            }
            return false;
        }
    });
}
function getBuilding(level_id) {
    $.ajax({
        xhrFields: {
            withCredentials: true
        },
        headers:{"Authorization":token},
        url: URL+"findLevelAll",
        dataType: 'json',
        type: 'post',
        success: function (data) {
            var strhtml = "<option></option>";
            $.each(data, function (index, item) {
                if (item.level_id == level_id) {
                    strhtml += "<option selected value='" + item.level_id + "'>" + item.level_name + "</option>"
                } else {
                    strhtml += "<option value='" + item.level_id + "'>" + item.level_name + "</option>"
                }
                //$('#buildId').append(new Option(item.level_name,item.level_id));// 下拉菜单里添加元素
            });
            $("#buildId").html(strhtml);
            layui.form.render("select");//重新渲染 固定写法
        }
    });
};

let treeData;
//获取数据源
function findall() {
    $.ajax({
        xhrFields: {
            withCredentials: true
        },
        headers:{"Authorization":token},
        url: URL+"getTree",
        data:{user_id:1},
        type: "POST",
        contentType: "application/json",
        async: false,
        success: function(data) {
            treeData = JSON.stringify(data);
            console.log(treeData);
        }
    })
}
layui.config({
    base : '../adview/js/layui/treetable-lay/'
});
layui.use(['treetable', 'table', 'layer'], function () {
    var table = layui.table;
    var layer = layui.layer;
    var treetable = layui.treetable;
    //渲染表格
    var renderTable = function () {
        layer.load(2);
        treetable.render({
            xhrFields: {
                withCredentials: true
            },
            headers: {"Authorization": token},
            id: 'privileges',
            treeColIndex: 1,	//树形图标显示在第几列
            treeSpid: '0',		//最上级的父级id
            treeIdName: 'id',	//id字段的名称
            treePidName: 'pid',	//pid字段的名称，父级菜单id
            treeDefaultClose: false,	//是否默认折叠
            treeLinkage: false,		//父级展开时是否自动展开所有子级
            elem: '#privileges',	//表格id
            url: URL + 'getTreeTable1',
            page: false,
            width:"250px",
            cols: [[
                {type: 'checkbox'},
                {field: 'name'},
                {field: 'id'}
            ]],
            //数据渲染完的回调
            done: function (res, page, count) {
                //关闭加载
                layer.closeAll('loading');
            }
        })
    };
    renderTable();
});
function zhixing1(){
    layer.open({
        //layer提供了5种层类型。可传入的值有：0（信息框，默认）1（页面层）2（iframe层）3（加载层）4（tips层）
        type: 1,
        title: "编辑管理员权限",
        area: ['550px', '410px'],
        maxmin: true, //允许全屏最小化
        anim: 1, //0-6的动画形式，-1不开启
        content: $('#quanxian'),//引用的弹出层的页面层的方式加载修改界面表单
        success: function(layero,index){
            //在回调方法中的第2个参数“index”表示的是当前弹窗的索引。
            //通过layer.full方法将窗口放大。
            layer.full(index);
        },
        cancel: function(index, layero){
            if(confirm('确定要关闭么')){ //只有当点击confirm框的确定时，该层才会关闭
                location.reload(true);
            }
            return false;
        }
    });
}
   /* layui.use(['form', 'tree'], function() {
        findall();
        let form = layui.form,
            tree = layui.tree,
            layer = layui.layer;
        privilege_tree();
        let privilege_tree = tree.render({
            elem: '#privileges',
            data: treeData,
            showCheckbox: true,  //是否显示复选框
            id: 'privileges',
            isJump: true //是否允许点击节点时弹出新窗口跳转
        });
        /!* let checked = $("#privilege").val();//获得角色已有权限
         console.log(check);
         let check = JSON.parse(checked);//（转换格式 '[2,3]'-->[2,3]）
         tree.setChecked('id', check); //设置勾选节点（显示已有权限）
         form.on("submit(save)", function(fm) {
             let checkData = privilege_tree.getChecked('PriId'); //获取勾选节点数据
             if(checkData.length == 0) {
                 layer.msg("至少勾选一个功能点！", {icon: 5, time: 1000});
                 return;
             }
             let privileges = [];
             for(let i in checkData) {
                 for(let j in checkData[i].children) {
                     for(let k in checkData[i].children[j].children) {
                         privileges.push(checkData[i].children[j].children[k].id);//保存最后子节点id
                     }
                 }
             }
             let field = fm.field;
             $.ajax({
                 url: "/role",
                 type: "PUT",
                 contentType: "application/json",
                 data: JSON.stringify({
                     "roleId": field.roleId,
                     "name": field.name,
                     "remark": field.remark,
                     "privilege": privileges
                 }),
                 dataType: "json",
                 success: function(res) {
                     if(res.code !== 0) {
                         layer.msg(res.message, {icon: 5, time: 1000});
                     }
                     else {
                         layer.msg("编辑成功", {icon: 6, time: 1000}, function() {
                             parent.layer.closeAll();
                             parent.layui.table.reload("mTable");
                         });
                     }
                 }
             });
         });*!/
    });
*/